using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Identity;
using Volo.Abp.Domain.Repositories;
using WMSSystem.YSL;

namespace WMSSystem.Application.Workflow
{
    /// <summary>
    /// 用户角色服务
    /// </summary>
    public class UserRoleService
    {
        private readonly IRepository<IdentityUser, Guid> _userRepository;
        private readonly IRepository<IdentityRole, Guid> _roleRepository;
        private readonly IRepository<UserLogin, Guid> _userLoginRepository;

        public UserRoleService(
            IRepository<IdentityUser, Guid> userRepository,
            IRepository<IdentityRole, Guid> roleRepository,
            IRepository<UserLogin, Guid> userLoginRepository)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _userLoginRepository = userLoginRepository;
        }

        /// <summary>
        /// 获取用户角色列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色名称列表</returns>
        public async Task<List<string>> GetUserRolesAsync(Guid userId)
        {
            // 首先尝试从 ABP Identity 系统获取角色
            var user = await _userRepository.GetAsync(userId);
            if (user != null)
            {
                // 从用户的角色集合中获取角色
                var roles = await _roleRepository.GetListAsync();
                var userRoles = roles.Where(r => user.Roles.Any(ur => ur.RoleId == r.Id)).ToList();
                if (userRoles.Any())
                {
                    return userRoles.Select(x => x.Name).ToList();
                }
            }

            // 如果 ABP Identity 中没有角色，尝试从自定义 UserLogin 系统获取
            var customUser = await _userLoginRepository.FirstOrDefaultAsync(x => x.Id == userId);
            if (customUser != null)
            {
                // 这里可以根据 UserLogin 的字段来判断角色
                // 例如：根据用户名、邮箱等字段来判断角色
                return GetCustomUserRoles(customUser);
            }

            return new List<string>();
        }

        /// <summary>
        /// 根据自定义用户信息获取角色
        /// </summary>
        /// <param name="user">自定义用户</param>
        /// <returns>角色列表</returns>
        private List<string> GetCustomUserRoles(UserLogin user)
        {
            var roles = new List<string>();
            
            // 只使用 RealName 作为角色字段
            if (!string.IsNullOrEmpty(user.RealName))
            {
                // 使用角色映射辅助类获取角色代码
                var roleCode = RoleMappingHelper.GetRoleCode(user.RealName);
                roles.Add(roleCode);
            }
            else
            {
                // 如果 RealName 为空，设置默认角色
                roles.Add("Manager"); // 默认经理权限
            }
            
            return roles;
        }

        /// <summary>
        /// 检查用户是否有指定角色
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="roleName">角色名称</param>
        /// <returns>是否有该角色</returns>
        public async Task<bool> HasRoleAsync(Guid userId, string roleName)
        {
            var userRoles = await GetUserRolesAsync(userId);
            return userRoles.Contains(roleName);
        }

        /// <summary>
        /// 根据用户角色确定审批步骤
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>审批步骤名称</returns>
        public async Task<string> DetermineApprovalStepAsync(Guid userId)
        {
            var userRoles = await GetUserRolesAsync(userId);
            
            // 根据角色确定审批步骤
            if (userRoles.Contains("Manager"))
            {
                return "ManagerApproval";
            }
            else if (userRoles.Contains("Finance"))
            {
                return "FinanceApproval";
            }
            else if (userRoles.Contains("WarehouseManager"))
            {
                return "WarehouseManagerApproval";
            }
            
            // 默认返回经理审批
            return "ManagerApproval";
        }

        /// <summary>
        /// 获取用户审批权限描述
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>权限描述</returns>
        public async Task<string> GetUserApprovalPermissionDescriptionAsync(Guid userId)
        {
            var userRoles = await GetUserRolesAsync(userId);
            
            if (userRoles.Contains("Manager"))
            {
                return "经理审批权限";
            }
            else if (userRoles.Contains("Finance"))
            {
                return "财务审批权限";
            }
            else if (userRoles.Contains("WarehouseManager"))
            {
                return "仓库管理员审批权限";
            }
            
            return "无审批权限";
        }
    }
} 